package com.iakuil.app.common.core.jsr303.validators;

import com.iakuil.app.common.core.enums.PasswordStrategy;
import com.iakuil.app.common.core.jsr303.constraints.Password;
import com.iakuil.app.common.core.util.StringUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * 密码校验器
 *
 * @author zenglei
 * @date 2020-11-27
 */
public class PassWordValidator implements ConstraintValidator<Password, String> {

    private PasswordStrategy strategy;

    @Override
    public void initialize(Password constraintAnnotation) {
        this.strategy = constraintAnnotation.strategy();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext context) {
        // 为空时，默认不校验，即认为通过
        if (StringUtils.isBlank(s)) {
            return true;
        }

        // 校验通过
        if (s.matches(strategy.getRegx())) {
            return true;
        }

        // 校验不通过
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()
            .replaceAll("\\{value}", strategy.getErrMsg())).addConstraintViolation();
        return false;
    }
}
